<?php


class NlogApi extends ApiBase
{
	private static $mongo = null;

	/**
	 * 构造函数，初始化插件
	 */
	public function __construct() 
	{
		parent::__construct();
		if(is_null(self::$mongo))
		{
			self::$mongo = n_api('mongo');
		}
	}

	/*
	 *debug日志记录
	 */
	public function debug($plugin, $scode, $utype='', $content)
	{
		if(empty($plugin) || empty($scode) || empty($content))
		{
			echo "nlog参数错误";
			return;
		}

		$data = array(
			'errtype' => 'debug',
			'plugin' => $plugin,
			'scode' => $scode,
			'utype' => $utype,
			'content' => $content,
			'time' => time()
		);
		
		self::$mongo->cnameAbsolute('dmslog')->insert('applog', $data);
	}

	/*
	 *error日志记录
	*/
	public function error($plugin, $scode, $utype='', $content) 
	{
		if(empty($plugin) || empty($scode) || empty($content))
		{
			echo "nlog参数错误, plugin: "  .$plugin . "; scode: " . $scode . "; utype: " . $utype . "; content: " . $content;
			return;
		}

		$data = array(
			'errtype' => 'error',
			'plugin' => $plugin,
			'scode' => $scode,
			'utype' => $utype,
			'content' => $content
		);

		$msg = json_encode($data);

		$sock = socket_create(AF_UNIX, SOCK_STREAM, 0);
		if ( !$sock ) {
			n_logSave("sock.log", 'create socket error');
		}

		$result = socket_connect($sock, '/tmp/nlog.sock');
		if ( !$result ) {
			n_logSave("sock.log", 'connect socket error : ' , socket_strerror(socket_last_error($sock)));
		}

		$head = 'dmslogHeader-0.1';
		
		$send = $head . pack('N', strlen($msg)) . $msg;

		$write = socket_write( $sock, $send);
		if ( !$write ) {
			n_logSave("sock.log", 'write socket error : ' , socket_strerror(socket_last_error($sock)));
		}

		socket_close( $sock );
	}

	/*
	 *info日志
	*/
	public function info($plugin, $utype='', $content)
	{
		if(empty($plugin) || empty($content))
		{
			echo "nlog参数错误";
			return;
		}

		$data = array(
			'errtype' => 'info',
			'plugin' => $plugin,
			'utype' => $utype,
			'content' => $content,
			'time' => time()
		);
		
		self::$mongo->cnameAbsolute('dmslog')->insert('applog', $data);
	}

	/*
	 *缓存日志
	*/
	public function addOriginData($scode, $param)
	{
		if(empty($scode) || empty($param) || !is_array($param))
		{
			trigger_error("参数错误", E_USER_ERROR);
		}

		$rs['ctime'] = time();
		$rs['scode'] = $scode;
		$rs['dtype'] = $dtype;
		$rs['content'] = json_encode(http_build_query($param));

		self::$mongo->cnameAbsolute('dmslog')->insert('recoverlog', $rs);
	}

	/*
	 *原始日志
	 */
	public function originLog($param)
	{
		if(empty($param) || !is_array($param))
		{
			trigger_error("原始日志param必须为数组", E_USER_ERROR);
		}

		return self::$mongo->cnameAbsolute('origin_data')->insert('origin_data', $param);
	}

	public function updateOriginLog($rs, $query)
	{
		if(empty($rs) || !is_array($rs) || empty($query) || !is_array($query))
		{
			trigger_error("更新原始日志参数错误", E_USER_ERROR);
		}

		self::$mongo->cnameAbsolute('origin_data')->update('origin_data', $query, $rs);
	}
}